package com.ruoyi.statisticalCenter.controller;

import cn.hutool.core.net.URLEncoder;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.domain.vo.InitTableVo;
import com.ruoyi.common.domain.vo.TableVo;
import com.ruoyi.common.service.TableService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.cache.CustomCacheFilter;
import com.ruoyi.hqfinance.domain.HqBargainPriceCollect;
import com.ruoyi.hqfinance.domain.HqNetworkBillDetail;
import com.ruoyi.logistic.domain.PageDate;
import com.ruoyi.logistic.domain.PageInfo;
import com.ruoyi.logistic.utils.TableUtils;
import com.ruoyi.statisticalCenter.domain.*;
import com.ruoyi.statisticalCenter.domain.vo.*;
import com.ruoyi.statisticalCenter.service.ScOutReturnSheetService;
import com.ruoyi.statisticalCenter.service.ScOutboundEliminateService;
import com.ruoyi.statisticalCenter.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sc/outReturnSheet")
@Api(tags = "统计中心-出港返利毛利表")
public class ScOutReturnSheetController {
    @Autowired
    private ScOutReturnSheetService scOutReturnSheetService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private ScOutboundEliminateService scOutboundEliminateService;
    @Autowired
    private TableService tableService;
    @Autowired
    private RedisUtil redisUtil;

    //@CustomCacheFilter
    @ApiOperation("汇总")
    @PostMapping("/collect")
    public R collect(@RequestBody ScOutReturnSheetVo vo) {
        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }
//        String list = scOutboundEliminateService.select().toString();

        // 构建Redis键
        String redisKey = "sc_out_return_sheet:collect:" + vo.getStartTime() + ":" + vo.getEndTime()
                + ":" + vo.getNetworkLevel() + + +vo.getPageDate().getPageNum() + vo.getPageDate().getPageSize();
        // 检查Redis中是否存在数据
        /*R redisResult = redisUtil.getObject(redisKey, R.class);
        if (redisResult != null) {
            return redisResult; // 如果Redis中存在数据，则直接返回
        }*/
        // 如果Redis中不存在数据，则从数据库中查询
        R databaseResult = scOutReturnSheetService.collectCache(vo);
        if (databaseResult.getCode() != 200) {
            databaseResult = scOutReturnSheetService.collect(vo);
        }
        // 将数据库查询结果存储到Redis，并设置过期时间为一天
        redisUtil.setObject(redisKey, databaseResult, 2400);
        return databaseResult;
    }

    @ApiOperation("cache")
    @PostMapping("cache")
    public R cache(@RequestBody DateStrVo time) {
        return scOutReturnSheetService.cache(time);
    }

    @ApiOperation("selectChild")
    @PostMapping("/selectChild")
    public R selectChild(@RequestBody ScOutReturnSheetChildVo vo) {
        return R.ok(scOutReturnSheetService.selectChildList(vo));
    }

    @ApiOperation("cacheChild")
    @PostMapping("cacheChild")
    public R cacheChild(@RequestBody DateStrVo time) {
        return scOutReturnSheetService.cacheChild(time);
    }


    @ApiOperation("点击跳转")
    @PostMapping("/point")
    public R point(@RequestBody ScOutReturnSheetPointVo vo) {
        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }
        List<HqNetworkBillDetail> list = scOutReturnSheetService.point(vo);
        List<TableVo> fieldList = tableService.getFieldAnnotation(new HqNetworkBillDetail());
        return TableUtils.handleListResponse(list, fieldList, "暂无数据");

    }

    @ApiOperation("导出")
    @PostMapping("/export")
    public R export(@RequestBody ScOutReturnSheetVo vo) {
//        if (vo != null) {
//            String startTime = vo.getStartTime().replace("-", "");
//            String endTime = vo.getEndTime().replace("-", "");
//            vo.setStartTime(startTime);
//            vo.setEndTime(endTime);
//            PageDate pageDate = new PageDate();
//            pageDate.setPageNum(1);
//            pageDate.setPageSize(50);
//            vo.setPageDate(pageDate);
//        }
//        String fileName = "attachment;filename=" + URLEncoder.createDefault().encode("总部收支汇总报表", Charset.forName("utf-8")) + ".xlsx";
//        response.setHeader("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
//        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
////        List<ScOutReturnSheet> list = scOutReturnSheetService.collectList(vo);
////        ExcelUtil<ScOutReturnSheet> util = new ExcelUtil(ScOutReturnSheet.class);
////        util.exportExcel(response, list, "总部收支汇总报表");
//        ServletOutputStream outputStream = null;
//        try {
//            outputStream = response.getOutputStream();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        scOutReturnSheetService.collectList(vo, outputStream);

        if (vo == null) {
            return R.fail("参数不能为空");
        }

        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
            PageDate pageDate = new PageDate();
            pageDate.setPageNum(1);
            pageDate.setPageSize(100);
            vo.setPageDate(pageDate);
        }

        // 检查是否有最近2分钟内的相同请求记录

        // 调用服务进行异步导出
        scOutReturnSheetService.exportAsync(vo);

        return R.ok("请前往总部下载中心查询进度");
    }

    @ApiOperation("显示配置列表")
    @GetMapping("/selectAll")
    public R selectAll() {
        ScOutBoundReturnSheetSet scOutBoundReturnSheetSet = scOutReturnSheetService.select();
        com.alibaba.fastjson.JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", scOutBoundReturnSheetSet);
        jsonObject.put("fields", scOutReturnSheetService.initTable());

        return R.ok(jsonObject);
    }

    @ApiOperation("修改配置列表")
    @PostMapping("/update")
    public R update(@RequestBody ScOutBoundReturnSheetSet sheetSet) {
        boolean isUpdate = scOutReturnSheetService.update(sheetSet);
        if (isUpdate) {
            return R.ok("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }

    /**
     * 导入
     */
    @ApiOperation("导入")
    @PostMapping("/importStudent")
    @ResponseBody
    public R importStudent(@RequestPart(value = "file") MultipartFile file) throws Exception {
        ExcelUtil<ScOutboundEliminate> util = new ExcelUtil<ScOutboundEliminate>(ScOutboundEliminate.class);
        List<ScOutboundEliminate> studentList = util.importExcel(file.getInputStream());
        return scOutboundEliminateService.importStudent(studentList);
    }

    @ApiOperation("下载模板")
    @GetMapping("/downloadTemplate")
    public void downloadTemplate() {
        String fileName = "attachment;filename=" + URLEncoder.createDefault().encode("剔除票数模板", Charset.forName("utf-8")) + ".xlsx";
        response.setHeader("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        List<ScOutboundEliminate> list = scOutboundEliminateService.select();
        ExcelUtil<ScOutboundEliminate> util = new ExcelUtil(ScOutboundEliminate.class);
        util.exportExcel(response, list, "剔除票数模板");
    }

    @ApiOperation("客户配置")
    @PostMapping("/updateClient")
    public R updateClient(@RequestBody ScOutReturnSheetClient scOutReturnSheetClient) {
        Boolean isUpdate = scOutReturnSheetService.updateClient(scOutReturnSheetClient);
        if (isUpdate) {
            return R.ok("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }

    @ApiOperation("查询客户配置")
    @GetMapping("/selectClientById")
    public R selectClientById(Integer id){
        ScOutReturnSheetClient client = scOutReturnSheetService.selectClientSet(id);
        List<TableVo> fieldList = tableService.getFieldAnnotation(new ScOutReturnSheetClient());
        return TableUtils.handleObjectResponse(client, fieldList, "暂无数据");
    }
}
